package cn.bugstack.chatgpt.data.domain.openai.service.channel.impl;

import cn.bugstack.chatglm.model.ChatCompletionRequest;
import cn.bugstack.chatglm.model.ChatCompletionResponse;
import cn.bugstack.chatglm.model.EventType;
import cn.bugstack.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.bugstack.chatgpt.data.domain.openai.service.channel.OpenAiGroupService;
import cn.bugstack.chatgpt.data.types.exception.ChatGLMException;
import cn.bugstack.deepseek.executor.parameter.ChatChoice;
import cn.bugstack.deepseek.executor.parameter.CompletionRequest;
import cn.bugstack.deepseek.executor.parameter.CompletionResponse;
import cn.bugstack.deepseek.executor.parameter.Message;
import cn.bugstack.deepseek.session.OpenAiSession;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeepSeekService implements OpenAiGroupService {

    @Resource
    protected OpenAiSession deepSeekOpenAiSession;

    @Override
    public void doMessageResponse(ChatProcessAggregate chatProcess, ResponseBodyEmitter emitter) {
        // 1. 请求消息
        List<Message> messages = chatProcess.getMessages().stream()
                .map(entity -> Message.builder()
                        .role(CompletionRequest.Role.valueOf(entity.getRole().toUpperCase()))
                        .content(entity.getContent())
                        .name(entity.getName())
                        .build())
                .collect(Collectors.toList());

        // 2. 封装参数
        CompletionRequest request = CompletionRequest.builder()
                .stream(true)
                .messages(messages)
                .model(chatProcess.getModel())
                .build();

        // 3.请求应答
        try {
            deepSeekOpenAiSession.completions(request, new EventSourceListener() {
                @Override
                public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
                    try {
                        // 解析返回的结果
                        CompletionResponse response = JSON.parseObject(data, CompletionResponse.class);
                        List<ChatChoice> choices = response.getChoices();
                        for (ChatChoice chatChoice : choices) {
                            Message delta = chatChoice.getDelta();
                            if (CompletionRequest.Role.ASSISTANT.getCode().equals(delta.getRole())) continue;
                            //应答完成
                            String finishReason = chatChoice.getFinishReason();
                            if (StringUtils.isNoneBlank(finishReason) && "stop".equals(finishReason)) {
                                emitter.complete();
                                return;
                            }
                            emitter.send(delta.getContent());
                        }
                    }catch (Exception ex){
                        try {
                            // 返回异常内容，但要保证是字符串
                            emitter.send(data); // ⚠️ data 必须是 JSON 字符串，而不是对象
                        } catch (IOException e) {
                            log.error("emitter.send(data) 失败", e);
                        } finally {
                            emitter.complete();
                        }
                    }
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
